package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler2 implements TypeHandler<Integer[]> {
    @Autowired
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        System.out.println("由Integer[]往String转化");
        String value = null;
        try {
            value = objectMapper.writeValueAsString(integers);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        preparedStatement.setString(i, value);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, String s) throws SQLException {
        System.out.println("String往Integer[]转化");
        String result = resultSet.getString(s);

        return transfer(result);
    }

    private Integer[] transfer(String result) {
        System.out.println("String往Integer[]转化 正在调用Transfer方法");
        Integer[] integers = new Integer[0];
        if (result == null || "".equals(result)) {
            System.out.println("transfer integers = " + integers+"为空！");
            return new Integer[0];
        }
            try {
                integers = objectMapper.readValue(result, Integer[].class);
                System.out.println("transfer objectMapper integers = " + integers+"执行了！");
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return integers;

    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int i) throws SQLException {
        System.out.println("String往Integer[]转化");
        String result = resultSet.getString(i);

        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        System.out.println("String往Integer[]转化");
        String result = callableStatement.getString(i);

        return transfer(result);

    }
}
